/*
 * @Description: 身份验证
 * @Author: lihk
 * @Date: 2024-10-08 17:03:20
 */
import { Injectable, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable } from 'rxjs';
import { JwtService } from '../services/jwt.service';
import { Reflector } from '@nestjs/core';

@Injectable()
export class JwtAuthGuard {
  constructor(
    private jwtService: JwtService, private reflector: Reflector
  ) { }
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const authHeader = request.header('Authorization');
    const excludeAuth = this.reflector.get('excludeAuth', context.getHandler());
    if (excludeAuth) {
      return true; // 如果路由有 @ExcludeAuth 装饰器，则跳过验证
    }
    if (authHeader && authHeader.startsWith('Bearer ')) {//有Authorization并且格式为 Bearer XXXXX 
      const token = authHeader.split(' ')[1];
      // 从数据库验证 token
      const decodedToken = this.jwtService.verifyToken(token);
      if (decodedToken) {
        // 如果令牌有效，将其添加到请求中
        request.user = decodedToken;
        return true;
      }
    }
    throw new HttpException('token无效', HttpStatus.UNAUTHORIZED);
  }
}